import path from 'path';
import Koa from 'koa';
import dotenv from 'dotenv/config'; // 处理.env环境变量
import Router from 'koa-router';
import koaBody from 'koa-body'; // body parser middleware
import json from 'koa-json'; // JSON pretty-printed response middleware
import statics from 'koa-static';
import compose from 'koa-compose';
import compress from 'koa-compress';
import allRouter from './routes/routes';

const app = new Koa();
const router = new Router();

const isDevMode = process.env.NODE_ENV !== 'production';

// 使用koa-compose集成中间件
const middleware = compose([
  koaBody({
    onError: (err) => {
      console.log('koabody tcl:err', err);
    },
  }),
  statics(path.join(__dirname, '../public')),
  json({ pretty: false, param: 'pretty' }),
]);

// 如果是生产模式，则压缩代码
if (!isDevMode) {
  app.use(compress());
}

app.use(middleware);
app.use(allRouter());

// 拦截器，拦截应用中没有的请求，返回4xx错误或者5xx错误
app.use(router.allowedMethods());

app.listen(process.env.SERVER_PORT);
